package com.cloudptt.wp.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.Const;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.adapter.GCallEventAdapter;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.message.MsgListener;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.listener.ProfileListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.operator.MsgOperator;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.address.workspace.FuncNumFragment;
import com.cloudptt.wp.ui.dlg.UiDlg;
import com.cloudptt.wp.ui.fragment.WorkSpaceFragment;
import com.cloudptt.wp.ui.listen.CallBack;
import com.cloudptt.wp.ui.listen.FloorStateListen;
import com.cloudptt.wp.ui.listen.IAddrUpdate;
import com.cloudptt.wp.ui.listen.IDiaNumGet;
import com.cloudptt.wp.ui.message.IMsgCallBack;
import com.cloudptt.wp.ui.message.MessageFragment;
import com.cloudptt.wp.ui.message.SessionActivity;
import com.cloudptt.wp.ui.more.SettingActivity;
import com.cloudptt.wp.ui.views.DialLayout;
import com.cloudptt.wp.ui.views.IMainTitleBtnAction;
import com.cloudptt.wp.ui.views.MainTitleLayout;
import com.cloudptt.wp.ui.views.PTTLayout;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.user.profile.UserProfile;
import com.mcptt.db.model.AddrInfo;
import com.mcptt.db.model.HistoryInfo;

import java.util.Iterator;
import java.util.List;


public class MainActivity extends BaseActivity implements View.OnClickListener, CallBack
        , ProfileListener, FloorStateListen,MsgListener, IMsgCallBack, IAddrUpdate, DialogInterface.OnClickListener, IMainTitleBtnAction, IDiaNumGet {

    public final static String KEY_HOME = "HomeActivity";
    public final static String KEY_NAME_ISFIRST = "isFirstLogin";

    private ImageView diaOpenIv;
    private TextView messageNum;
    private FrameLayout mainFragment;
    private MainTitleLayout mainTitleLayout = null;
    private DialLayout dialLayout = null;
    private PTTLayout mNewPtt;
    private Product product;
    private McIdInfo myInfo;
    private ContactFragment contactFragment;
    //	private MapFragment mapFragment;
    private MessageFragment messageFragment;
    private FuncNumFragment funcNumFragment;

    private GCallEventAdapter callEventAdapter = null;
//    private PowerManager.WakeLock wakeLock;

    //    private boolean isKeepAlive = true;
    private AddrInfo callAddrInfo = null;

    private RadioGroup mTabRadioGroup;
    private SparseArray<Fragment> mFragmentSparseArray;
    private int curCheckedId = R.id.tab_session;
    /** permission request 2019/07/15 **/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.gradient_end));

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        initNotificationLayout();
        mainFragment = ( findViewById(R.id.main_fragment));
        mainTitleLayout = (MainTitleLayout)findViewById(R.id.mainTitleLayout);
        mainTitleLayout.setAction(this);

        dialLayout = (DialLayout)findViewById(R.id.diaLy);
        dialLayout.setAction(this);

        diaOpenIv = (ImageView)findViewById(R.id.diaOpenIv);
        diaOpenIv.setOnClickListener(this);
        diaOpenIv.setVisibility(View.GONE);

//        memberIv= (ImageView)findViewById(R.id.memberIv);
//        memberIv.setOnClickListener(this);
//        memberIv.setVisibility(View.GONE);

//        groupCallHangupIv= (ImageView)findViewById(R.id.groupCallHangupIv);
//        groupCallHangupIv.setOnClickListener(this);
//        groupCallHangupIv.setVisibility(View.GONE);
        messageNum = (TextView)findViewById(R.id.messageNum);
        // 通话状态提示栏
//        mNewNotificationLayout = (GroupcallStateLayout)findViewById(R.id.notification_new);
//        mOfflineStateLayout = (OfflineStateLayout) findViewById(R.id.offline_status_layout);
        // PTT模块
        mNewPtt = (PTTLayout)findViewById(R.id.ptt_new);
        mNewPtt.setDiaNumGet(this);

        checkCurVersion();
        initView();

        // Android 8.0+ 使用 startForegroundService()
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
//        {
//            Intent serviceIntent = new Intent(this, LockScreenService.class);
//            ContextCompat.startForegroundService(this, serviceIntent);
//        } else {
//            // 低版本直接 startService()
//            startService(new Intent(this, LockScreenService.class));
//        }
    }



    private void initView() {
        mTabRadioGroup = findViewById(R.id.tabs_rg);
        mFragmentSparseArray = new SparseArray<>();
        myInfo = getMyLoginInfo();
        Log.debug(this.getClass(), "initView myInfo = " + myInfo);
        AddrInfo info = null;
        if(myInfo != null)
        {
            String descStr = myInfo.getDscp();
            Log.debug(this.getClass(), "initView descStr = " + descStr);
            mainTitleLayout.setSelfName(descStr);
            info = myInfo.toAddrInfo();
        }
        else
        {
            info = new AddrInfo();
        }

        messageFragment = new MessageFragment(this,info,this,this);
        mFragmentSparseArray.append(R.id.tab_session, messageFragment);
        contactFragment = new ContactFragment(this,info,this);
        mFragmentSparseArray.append(R.id.tab_addr, contactFragment);
        funcNumFragment = new FuncNumFragment(this);
        mFragmentSparseArray.append(R.id.tab_func, funcNumFragment);
        mFragmentSparseArray.append(R.id.tab_workspace, new WorkSpaceFragment());
        mTabRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // 具体的fragment切换逻辑可以根据应用调整，例如使用show()/hide()
                curCheckedId = checkedId;
                if(checkedId == R.id.tab_session)
                {
                    mainTitleLayout.setTitle(R.string.main_title_session);
                    mainTitleLayout.setVisibility(View.VISIBLE);
//                    diaOpenIv.setVisibility(View.GONE);
                    if(!dialLayout.isShow()) {
                        diaOpenIv.setVisibility(View.GONE);
                    }
                }
                else if(checkedId == R.id.tab_addr)
                {
                    mainTitleLayout.setVisibility(View.GONE);
                    if(!dialLayout.isShow()) {
                        diaOpenIv.setVisibility(View.VISIBLE);
                    }
                }
                else if(checkedId == R.id.tab_func)
                {
                    mainTitleLayout.setTitle(R.string.main_title_func);
                    mainTitleLayout.setVisibility(View.VISIBLE);
//                    diaOpenIv.setVisibility(View.VISIBLE);
                    if(!dialLayout.isShow()) {
                        diaOpenIv.setVisibility(View.VISIBLE);
                    }
                }
                else if(checkedId == R.id.tab_workspace)
                {
                    mainTitleLayout.setTitle(R.string.main_title_workspace);
                    mainTitleLayout.setVisibility(View.VISIBLE);
//                    diaOpenIv.setVisibility(View.GONE);
                    if(!dialLayout.isShow()) {
                        diaOpenIv.setVisibility(View.GONE);
                    }
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment,
                        mFragmentSparseArray.get(checkedId)).commit();
            }
        });
        // 默认显示第一个
        getSupportFragmentManager().beginTransaction().add(R.id.main_fragment,
                mFragmentSparseArray.get(R.id.tab_session)).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.debug(this.getClass(), "onResume");
        requestWakeLock();
        initDiaOpenIv();
        this.setFloorStateListen(this);
        if(product == null){
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if( product != null)
        {
            this.product.setProfileListener(this);
            this.product.setMsgListener(this,null);
            myInfo = product.getSysConfig().getMcInfo();
            updateMyName();
            if(callEventAdapter == null)
            {
                callEventAdapter = product.getGCallEventAdapter();
            }
            mNewPtt.setCallAdapter(callEventAdapter);

            SysStateInfo sysStateInfo = product.getSysStateInfo();
            Log.debug(this.getClass(), "onResume sysStateInfo = " + sysStateInfo);
            int state = sysStateInfo.getState();
            int cause = sysStateInfo.getCause();

            if(SysStateInfo.SysState_SvrStartState == state)
            {
                if(SysStateInfo.Cause_Suc != cause)
                {
                    goToLogin();
                    return;
                }
            }

            boolean hasActivieGroupVideoCall = callEventAdapter.hasActivieGroupVideoCall();
            Log.debug(this.getClass(), "onResume hasActivieGroupVideoCall = " + hasActivieGroupVideoCall);
            if(hasActivieGroupVideoCall) {
                int callState = callEventAdapter.getCallState();
                mNewPtt.updateUiForCallState(callState);

                int floorState = callEventAdapter.getFloorState();
                AddrInfo info = callEventAdapter.getFloorAddrinfo();
                if(info != null) {
                    mNewPtt.updateUiForFloorState(floorState,false);
                }
                else
                {
                    mNewPtt.updateUiForFloorState(floorState,true);
                }
            }

        }
        printSrceenInfo();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 显示Dialog
                SysApplication app = ((SysApplication) getApplicationContext());
                if(app != null)
                {
                    app.checkIncommingDlg();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        Log.debug(this.getClass(), "onDestroy");
        super.onDestroy();
        this.releaseWakeLock();
//        unregisterReceiver(mResultReceiver);
    }

    @Override
    public void onTrimMemory(int level) {
        // TODO Auto-generated method stub
        super.onTrimMemory(level);
        Log.debug(this.getClass(),"onTrimMemory level = " + level);
    }

//	private void updateOnlineState(){
//		if(product == null){
//			SysApplication app = ((SysApplication) getApplicationContext());
//			this.product = app.getProduct();
//		}
//
//		if(product!=null
//				&& myInfo != null){
//			AddrOperator operator = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
//			List<GroupInfo> list = operator.getGroupListAndUserList();
//			if(contactFragment != null) {
//				contactFragment.updateData(list);
//			}
//			Log.d(TAG, "updateOnlineState list = " + list);
//		}
//	}




    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.debug(this.getClass(), "onPause");
//        getContentResolver().unregisterContentObserver(mGpsMonitor);
//		doPttOff(true);
//        SysApplication app = ((SysApplication) getApplicationContext());
//        this.product = app.getProduct();

        if(this.product !=null){
            this.product.setProfileListener(null);
//            product.setNetworkListener(null);
//            product.setUpdateListener(null);
//            product.setSysListener(null);
//			product.setAddrListener(null);
//            			product.setLbsListener(null);
            product.setMsgListener(null,null);
        }
        releaseWakeLock();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.debug(this.getClass(), "onStop");

        if(callEventAdapter != null)
        {
            mNewPtt.clearState();
            callEventAdapter = null;
            if(mNewPtt != null)
            {
                mNewPtt.onStop();
            }
        }
    }

    private void doPttOff(boolean isMust)
    {
        Log.debug(this.getClass(), "doPttOff");

        if(callEventAdapter != null)
        {
            callEventAdapter.onPtt(Const.MSG_TALK_OFF, true,false,false,false);
        }
    }

    @Override
    public void showTab(boolean showOrHide) {
        // TODO Auto-generated method stub
//        mViewPager.setScrollFlag(showOrHide);
    }






    @Override
    public void receiveMsg() {
        // TODO Auto-generated method stub
        //UiDlg.createWarningDialog(this, causeStr, R.drawable.black_face).show();
        Log.debug(this.getClass(), "receiveMsg");
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                updateHistoryInfoList();
            }
        });
    }


    public McIdInfo getMyLoginInfo()
    {
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if(product == null){
            return null;
        }else{
            return product.getMcpttLoginInfo().getMcIdInfo();
        }
    }
    public AddrInfo getCurGroupInfo()
    {
        Log.debug(this.getClass(), "getCurGroupInfo 1");
        if(product == null)
        {
            Log.debug(this.getClass(), "getCurGroupInfo 2");
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if(product != null)
        {
            AddrInfo info = product.getCurGroupInfo();
            Log.debug(this.getClass(), "getCurGroupInfo info = "+info);
            return info;
        }
        return null;
    }
    public void setDefaultGroupInfo(AddrInfo info)
    {
        Log.debug(this.getClass(), "setDefaultGroupInfo info = " + info);
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if(product != null)
        {
            product.setDefaultGroupInfo(info);
        }
        if(contactFragment != null)
        {
            contactFragment.updateAddrList(false);
        }
//		loadAddressAndOnline();
        updateHistoryInfoList();
    }

    @Override
    public void onCallState(String callKey, int callState) {
        Log.debug(this.getClass(), "onCallState callKey = " + callKey + " callState = " + callState);
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(mNewPtt != null)
                {
                    mNewPtt.updateUiForCallState(callState);
                }
            }
        });
    }

    /** permission request 2019/07/15 **/

    @Override
    public void onFloorState(String callKey,int floorState,boolean isIdle)
    {
        Log.debug(this.getClass(), "onFloorState callKey = " + callKey + " floorState = " + floorState + " isIdle = " + isIdle);
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(mNewPtt != null)
                {
                    mNewPtt.updateUiForFloorState(floorState,isIdle);
                }
            }
        });
    }


    private void initDiaOpenIv()
    {
        if(curCheckedId == R.id.tab_addr
                || curCheckedId == R.id.tab_func)
        {
            if (!dialLayout.isShow()) {
                diaOpenIv.setVisibility(View.VISIBLE);
            }
            else
            {
                diaOpenIv.setVisibility(View.GONE);
            }
        }
        else
        {
            diaOpenIv.setVisibility(View.GONE);
        }
    }



//    private void showPttLayout(boolean isShow){
//        mNewPtt.showCallBtn(isShow);
//    }


//    @Override
//    public void updateHasVoice(String callKey,int speakState,boolean hasVoice)
//    {
//        Log.debug(this.getClass(), "updateCallInfoDesc callKey = " + callKey + " hasVoice = " + hasVoice);
//        this.runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                if(mNewPtt != null)
//                {
//                    mNewPtt.updateUi(speakState,hasVoice);
//                }
////                if(mNewNotificationLayout != null) {
////                    mNewNotificationLayout.updateHasVoice(hasVoice);
////                }
//            }
//        });
//    }


    @Override
    public void updateHistoryInfoList()
    {
        Log.debug(this.getClass(), "updateHistoryInfoList");
        if(product == null){
            SysApplication app = ((SysApplication) getApplicationContext());
            product = app.getProduct();
        }
        if(product != null)
        {
            MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
            List<HistoryInfo> list = operator.getHistoryInfoList();
            Log.debug(this.getClass(), "updateHistoryInfoList list = " + list);
            if(messageFragment != null
                    && list != null
                    && list.size() >= 0)
            {
                int count = getUnReadCount(list);
                updateUnReadCount(count);
                messageFragment.updateHistoryRecords(list);
            }
        }
    }
    @Override
    public boolean delHirstoryRecord(HistoryInfo info) {
        // TODO Auto-generated method stub
        SysApplication app = ((SysApplication) getApplicationContext());
        Product product = app.getProduct();
        MsgOperator operator = (MsgOperator)product.getOperator(ProductConst.Func_Msg);
        String receiverUId = info.getPeerAddrInfo().getAddrId();//.getAddrInfo().getMcId();
        boolean isSuc = operator.delHirstory(receiverUId);
        return isSuc;
    }

    private void updateUnReadCount(int count)
    {
        if(count == 0)
        {
            messageNum.setVisibility(View.GONE);
        }
        else if(count > 99)
        {
            messageNum.setVisibility(View.VISIBLE);
            messageNum.setText("...");
        }
        else
        {
            messageNum.setVisibility(View.VISIBLE);
            messageNum.setText("" + count);
        }
//        bottomView.setMsgCount(0,count);
    }
    private int getUnReadCount(List<HistoryInfo> list)
    {
        int count = 0;
        for(Iterator<HistoryInfo> itor = list.iterator(); itor.hasNext();)
        {
            HistoryInfo info = itor.next();
            count = count + info.getUnreadCount();
        }
        return count;
    }




    @Override
    public void initConfigSuc(String fileName)
    {
        Log.debug(this.getClass(), "initConfigSuc fileName = " + fileName);

        if(UserProfile.FileName_Mcptt.equals(fileName))
        {
            myInfo = getMyLoginInfo();
            updateMyName();
            if(contactFragment !=null){
                contactFragment.updateAddrList(true);
            }
        }
//        else if(UeConfig.FileName.equals(fileName))
//        {
//            if(product == null)
//            {
//                SysApplication app = ((SysApplication) getApplicationContext());
//                product = app.getProduct();
//            }
//            if(product != null)
//            {
//                product.checkCurVersion(MainActivity.this,true,false,null);
//            }
//        }
    }
    @Override
    public void initConfigFailed(String fileName,String errStr)
    {

    }

    public void requestWakeLock() {
//        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        wakeLock = powerManager.newWakeLock(
//                PowerManager.SCREEN_BRIGHT_WAKE_LOCK
//                        | PowerManager.ACQUIRE_CAUSES_WAKEUP,
//                "com.cloudptt.wp.ui.MainActivity");
//        if (wakeLock != null)
//            wakeLock.setReferenceCounted(false);
//        if (wakeLock != null && !wakeLock.isHeld()) {
//            wakeLock.acquire();
//        }
    }

    private void releaseWakeLock()
    {
//        if (wakeLock != null && wakeLock.isHeld()) {
//            wakeLock.release();
//        }
    }

//	public void loadAddrList()
//	{
//		SysConfig config = product.getSysConfig();//.getServerInfo().getServerIp();
//		if(config != null)
//		{
//			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
//			op.loadAddress(config, this);//.loadAddressAndOnline(svrIp, this);
//		}
//	}

//	public void loadAddressAndOnline()
//	{
////		String svrIp = product.getSysConfig().getServerInfo().getServerIp();
////		if(svrIp != null)
////		{
////			AddrOperator op = (AddrOperator)product.getOperator(ProductConst.Func_Addr);
////			op.loadOnlineState(svrIp, this);
////		}
//	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
        {
            return true;
        }

        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_UP);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_DOWN);
                break;
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_MUTE);
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.debug(this.getClass(), "onKeyUp keyCode = " + keyCode);
        if(event.getKeyCode() == KeyEvent.KEYCODE_BACK)
        {
            return true;
        }

        switch (keyCode) {
//			case 142:
//				if(callEventAdapter != null)
//				{
//					callEventAdapter.onPtt(Const.MSG_TALK_OFF,false,true);
//				}
//				break;
            case KeyEvent.KEYCODE_VOLUME_UP:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_UP);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_DOWN);
                break;
            case KeyEvent.KEYCODE_VOLUME_MUTE:
                callEventAdapter.onVol(KeyEvent.KEYCODE_VOLUME_MUTE);
                break;
        }
        return super.onKeyUp(keyCode, event);
    }
    /** permission request 2019/07/15 **/
    public void printSrceenInfo()
    {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int width = displayMetrics.widthPixels; // 获取屏幕宽度（像素）
        int height = displayMetrics.heightPixels; // 获取屏幕高度（像素）
        Log.debug(this.getClass(),"printSrceenInfo displayMetrics : " + width + " x " + height);
    }
    @Override
    public void onClick(View v) {
        ScreenManager.getScreenManager().popAllActivityExceptOne(this,MainActivity.class);
        if(R.id.diaOpenIv == v.getId())
        {
            diaOpenIv.setVisibility(View.INVISIBLE);
            dialLayout.setShow(true);
            dialLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBtnAction(int action) {
        Log.debug(this.getClass(),"onBtnAction action = " + action);
        switch (action)
        {
            case R.id.settingsBtn:
                Intent intent = new Intent(MainActivity.this,
                        SettingActivity.class);
                startActivity(intent);
                overridePendingTransition( R.anim.in_from_left, R.anim.out_to_right );
                break;
            case R.id.queryBtn:
                break;
            case R.id.addBtn:
                break;
            case R.id.addRb:
                break;
            case R.id.saveRb:
                break;
            case R.id.callRb:
                doCallAction();
                break;
            case R.id.msgRb:
                doMsgAction();
                break;
            case R.id.diaCloseIv:
            case R.id.blankView:
                if(curCheckedId == R.id.tab_addr
                        || curCheckedId == R.id.tab_func)
                {
                    diaOpenIv.setVisibility(View.VISIBLE);
                }
                else
                {
                    diaOpenIv.setVisibility(View.GONE);
                }
                dialLayout.setShow(false);
                dialLayout.setVisibility(View.INVISIBLE);
                dialLayout.clear();
                break;
        }
    }
    public void doCallAction()
    {
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        AddrInfo peerAddrInfo = null;
        String numStr = dialLayout.getNumStr();
        Log.debug(this.getClass(),"doCallAction numStr = " + numStr);
        if(numStr != null
                && numStr.trim().length() > 0)
        {
            if(numStr != null
                    && numStr.trim().length() > 0)
            {
                int type = AddrInfo.getUserTypeByNum(numStr);
                Log.debug(this.getClass(), "doCallAction type = " + type);
                if(type == AddrInfo.UserType_Func)
                {
                    peerAddrInfo = new AddrInfo(AddrInfo.UserType_Func, numStr, numStr, 0);
                }
                else if(type == AddrInfo.UserType_User)
                {
                    peerAddrInfo = product.getUserInfoByNum(numStr);
                }
                else if(type == AddrInfo.UserType_Dac)
                {
                    peerAddrInfo = product.getUserInfoByNum(numStr);
                }
                else
                {
                    peerAddrInfo = new AddrInfo(AddrInfo.UserType_User, numStr, numStr, 0);
                }
                Log.debug(this.getClass(), "doCallAction peerAddrInfo = " + peerAddrInfo);
                if(peerAddrInfo != null
                        && peerAddrInfo.isUserType())
                {
                    this.callAddrInfo = peerAddrInfo;
                    Log.debug(this.getClass(), "doCallAction showListDialog");
                    String item1 = getString(R.string.single_call_voice);
                    String item2 = getString(R.string.single_call_video);
                    String item3 = getString(R.string.single_call_video_pull);
                    String item4 = getString(R.string.single_call_video_push);
                    String[] list = new String[]{item1,item2,item3,item4};
                    UiDlg.showListDialog(this, list, this);
                }
            }
        }
    }
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Log.debug(this.getClass(), "onClick which = " + which + " peerAddrInfo = " + callAddrInfo);
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        if(this.callAddrInfo != null)
        {
            int callType = CallAttr.CallType_Private;
            boolean hasVideo = false;
            if(which == 1
                    || which == 2
                    || which == 3)
            {
                hasVideo = true;
                if(which == 2)
                {
                    callType = CallAttr.CallType_Pull_One_To_One;
                }
                else if(which == 3)
                {
                    callType = CallAttr.CallType_Push_One_To_One;
                }
            }
            String curFuncNum = "";
            if(callAddrInfo.isFuncType())
            {
                curFuncNum = getCurFuncNum();
                Log.debug(this.getClass(),  "onClick curFuncNum = " + curFuncNum);
                if(curFuncNum == null
                        || curFuncNum.equals(""))
                {
                    CommDlg.showToast(MainActivity.this,R.string.func_src_num_check);
                    return;
                }
            }
            product.getPCallEventAdapter().makePrivateCall(callAddrInfo, callType,hasVideo,false,curFuncNum);
        }
    }
    private String getCurFuncNum()
    {
        SysApplication app = ((SysApplication) getApplicationContext());
        Product product = app.getProduct();
        if(product != null)
        {
            SysConfig config = product.getSysConfig();
            return config.getCurFuncNum();
        }
        return "";
    }

    public void doMsgAction()
    {
        if(product == null)
        {
            SysApplication app = ((SysApplication) getApplicationContext());
            this.product = app.getProduct();
        }
        String numStr = dialLayout.getNumStr();
        Log.debug(this.getClass(),"doMsgAction numStr = " + numStr);
        if(numStr != null
                && numStr.trim().length() > 0)
        {
            AddrInfo peerAddrInfo = null;
            String nameStr = numStr;
            boolean isEmergency = false;
            int type = AddrInfo.getUserTypeByNum(numStr);
            Log.debug(this.getClass(), "doCallAction type = " + type);
            if(type == AddrInfo.GroupType_Crsc)
            {
                if (numStr.endsWith("299")) {
                    isEmergency = true;
                }
                if (numStr.length() == 3) {
                    numStr = "50" + numStr;
                    nameStr = nameStr;
                }
                peerAddrInfo = new AddrInfo(AddrInfo.GroupType_Crsc, nameStr, numStr, 0);
            }
            else if(type == AddrInfo.GroupType_Normal)
            {
                peerAddrInfo = product.getGroupInfoByNum(numStr);
            }
            else if(type == AddrInfo.UserType_Func)
            {
                peerAddrInfo = new AddrInfo(AddrInfo.UserType_Func, numStr, numStr, 0);
            }
            else if(type == AddrInfo.UserType_User)
            {
                peerAddrInfo = product.getUserInfoByNum(numStr);
            }
            else if(type == AddrInfo.UserType_Dac)
            {
                peerAddrInfo = product.getUserInfoByNum(numStr);
            }
            else
            {
                peerAddrInfo = new AddrInfo(AddrInfo.UserType_User, numStr, numStr, 0);
            }
            if(peerAddrInfo != null)
            {
                Intent intent = new Intent(this, SessionActivity.class);
                intent.putExtra(SessionActivity.KEY, peerAddrInfo);
                this.startActivity(intent);
            }
        }
    }

    @Override
    public String getDiaNum() {
        if(dialLayout != null)
        {
            return dialLayout.getNumStr();
        }
        return "";
    }
    private void updateMyName(){
        if(myInfo != null){
            Log.debug(this.getClass(),"updateMyName myInfo = "+ myInfo);
            String descStr = myInfo.getDscp();
            mainTitleLayout.setSelfName(descStr);
        }
    }

    public void checkCurVersion(){
             if(product == null)
            {
                SysApplication app = ((SysApplication) getApplicationContext());
                product = app.getProduct();
            }
            if(product != null)
            {
                product.checkCurVersion(MainActivity.this,true,false,null);
            }
    }
}
